package com.rocching.easychat;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.CompositePageTransformer;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.rocching.easychat.core.IApiCallback;
import com.rocching.easychat.core.SubConversationListActivity;
import com.rocching.easychat.core.UserIdentityContext;
import com.rocching.easychat.model.FriendListModel;
import com.rocching.easychat.model.UserTokenModel;
import com.rocching.easychat.service.FriendService;
import com.rocching.easychat.service.UserService;
import com.rocching.easychat.ui.FragmentMe;
import com.rocching.easychat.ui.FriendListFragment;
import com.rocching.easychat.ui.MyConversationListFragment;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import io.rong.common.RLog;
import io.rong.imkit.RongIM;
import io.rong.imkit.activity.RongBaseActivity;
import io.rong.imkit.config.ConversationListBehaviorListener;
import io.rong.imkit.conversationlist.ConversationListFragment;
import io.rong.imkit.conversationlist.RongConversationListActivity;
import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imkit.conversationlist.model.GatheredConversation;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.userinfo.model.GroupUserInfo;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

public class MainActivity extends AppCompatActivity {
    private final String TAG = MainActivity.class.getName();

    private final List<Fragment> fragmentList = new LinkedList<>();
    private ViewPager2 viewPager;
    private BottomNavigationView navigationView;
    private ActivityResultLauncher<Intent> launcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    public void refreshFriendList() {
        initFriendList();
    }

    private void init() {
        initLauncher();
        initBottomNavigation();
        initFragments();
        initViewPager();
        initConnection();
        initConversationListBehaviorListener();
        initFriendList();
        initUserDataObserver();
    }

    private void initFragments() {
        MyConversationListFragment conversationListFragment = new MyConversationListFragment();
        FriendListFragment friendListFragment = new FriendListFragment();
        FragmentMe fragmentMe = new FragmentMe();

        fragmentList.add(conversationListFragment);
        fragmentList.add(friendListFragment);
        fragmentList.add(fragmentMe);
    }

    private void initViewPager() {
        viewPager = findViewById(R.id.vp_main_container);

        FragmentStateAdapter fragmentStateAdapter = new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getItemCount() {
                return fragmentList.size();
            }
        };

        viewPager.setAdapter(fragmentStateAdapter);
        viewPager.setOffscreenPageLimit(fragmentList.size());
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                navigationView.setSelectedItemId(getItemId(position));
            }
        });
    }

    private void initConnection() {
        UserService.getInstance().getToken(UserIdentityContext.getAccount(), new IApiCallback<UserTokenModel>() {
            @Override
            public void onResponse(boolean succeeded, String body, UserTokenModel data) {
                if (succeeded) {
                    RongIM.connect(data.getToken(), 600, new RongIMClient.ConnectCallback() {
                        @Override
                        public void onSuccess(String userId) {
                            showText(R.string.connected_tip);
                        }

                        @Override
                        public void onError(RongIMClient.ConnectionErrorCode connectionErrorCode) {
                            Log.i(TAG, connectionErrorCode.name());
                        }

                        @Override
                        public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus databaseOpenStatus) {
                            Log.i(TAG, databaseOpenStatus.name());
                        }
                    });
                } else {
                    Log.i(TAG, body);
                }
            }
        });
    }

    private void initFriendList() {
        FriendService.getInstance().getFriendList(new IApiCallback<FriendListModel>() {
            @Override
            public void onResponse(boolean succeeded, String body, FriendListModel data) {
                if (succeeded) {
                    if (!Objects.isNull(data)) {
                        FriendListFragment fragment = (FriendListFragment) fragmentList.get(1);
                        fragment.refreshData(data);
                    }
                } else {
                    Log.i(TAG, "error:" + body);
                }
            }
        });
    }

    private void initUserDataObserver() {
        RongUserInfoManager.getInstance().addUserDataObserver(new RongUserInfoManager.UserDataObserver() {
            @Override
            public void onUserUpdate(UserInfo info) {
                Log.i(TAG, "the user info is changed.");
                FriendListFragment friendListFragment = (FriendListFragment) fragmentList.get(1);
                friendListFragment.refreshDataByUser(info);

                FragmentMe fragmentMe = (FragmentMe) fragmentList.get(2);
                fragmentMe.refreshData();
            }

            @Override
            public void onGroupUpdate(Group group) {

            }

            @Override
            public void onGroupUserInfoUpdate(GroupUserInfo groupUserInfo) {

            }
        });
    }

    private void initBottomNavigation() {
        navigationView = findViewById(R.id.navigationView);

        navigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                viewPager.setCurrentItem(getItemIndex(item.getItemId()));
                return true;
            }
        });
    }

    private void initConversationListBehaviorListener() {
        RongIM.setConversationListBehaviorListener(new ConversationListBehaviorListener() {
            @Override
            public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String targetId) {
                return false;
            }

            @Override
            public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String targetId) {
                return false;
            }

            @Override
            public boolean onConversationLongClick(Context context, View view, BaseUiConversation conversation) {
                return false;
            }

            @Override
            public boolean onConversationClick(Context context, View view, BaseUiConversation conversation) {
                if (conversation != null && conversation.mCore != null) {
                    if (conversation instanceof GatheredConversation) {
                        skipConversationListActivity(((GatheredConversation) conversation).mGatheredType, conversation.mCore.getConversationTitle());
                    } else {
                        RouteUtils.routeToConversationActivity(view.getContext(), conversation.mCore.getConversationType(), conversation.mCore.getTargetId());
                    }
                }
                return true;
            }
        });
    }

    private void initLauncher() {
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Log.i(TAG, "the result code is:" + result.getResultCode());
                int resultCode = result.getResultCode();
                if (resultCode != Activity.RESULT_OK) {
                    return;
                }
                Intent data = result.getData();
                if (data == null) {
                    return;
                }

                boolean needRefresh = data.getBooleanExtra("needRefresh", false);
                Log.i(TAG, "the needRefresh is:" + needRefresh);
                if (needRefresh) {
                    refreshFriendList();
                }
            }
        });
    }

    private void skipConversationListActivity(Conversation.ConversationType type, String title) {
        Intent intent = new Intent(this, SubConversationListActivity.class);
        intent.putExtra(RouteUtils.CONVERSATION_TYPE, type);
        intent.putExtra(RouteUtils.TITLE, title);
        launcher.launch(intent);
    }

    private int getItemId(int index) {
        int itemId = 0;
        switch (index) {
            case 0:
                itemId = R.id.menu_message;
                break;
            case 1:
                itemId = R.id.menu_friend_list;
                break;
            case 2:
                itemId = R.id.menu_me;
                break;
            default:
                break;
        }
        return itemId;
    }

    @SuppressLint("NonConstantResourceId")
    private int getItemIndex(int itemId) {
        int index = 0;
        switch (itemId) {
            case R.id.menu_message:
                index = 0;
                break;
            case R.id.menu_friend_list:
                index = 1;
                break;
            case R.id.menu_me:
                index = 2;
                break;
            default:
                break;
        }
        return index;
    }

    private void showText(int resId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), getString(resId), Toast.LENGTH_SHORT).show();
            }
        });
    }
}